const db = require('../config/db')
//引入加密文件
const bcrypt = require('./bcrypt')
//引入token
const jwt = require('../dao/jwt')

let token
// const sqlstr = 'select * from userschema'
// db.query(sqlstr, (req, res) => {
//     console.log(res);

// })

//生成id
function createId() {


    var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
    for (var j = 0; j < 500; j++) { //500为想要产生的行数
        var result = "";
        for (var i = 0; i < 20; i++) {
            r = Math.floor(Math.random() * 16);
            result += data[r];
        }
        return result
    }
}
//新建用户
exports.buildUser = (data, res) => {


    let password = bcrypt.enctyption(data.password)
    let sqlstr = 'INSERT INTO userschema (name,email,psw,birth,_id,register) VALUES (?,?,?,?,?,?) '
    db.query(sqlstr, [data.name, data.email, password, new Date(), createId(), new Date()], (err, res1) => {



        if (err) return res.send({ status: 500, message: res1 })
        return res.send({ status: 200, message: '注册成功' })
    })
}

//查询是否注册
exports.countUserValues = (name, mail, res) => {
    let sqlstr = 'select * from userschema  where name=?&&email=?   '
    db.query(sqlstr, [name, mail], (err, res1) => {
        if (err) return res.send({ status: 500 })
        if (res1.length > 0) {
            return res.send({ status: 200, message: '已注册' })
        } else {
            return res.send({ status: 200, message: '未注册' })
        }

    })
}

//用户登录
exports.userMatch = (data, res) => {



    let sqlstr = 'select * from userschema  where name=? or email=? '
    db.query(sqlstr, [data.name, data.name], (err, res1) => {
        if (err) return res.send({ status: 500 })
        if (res1 == '') {
            return res.send({ status: 400 })
        } else {
            res1.map((e) => {
                const pwdMatch = bcrypt.verification(data.pwd, e.psw)
                if (pwdMatch) {
                    token = jwt.generateToken(e.id)
                    let back = {
                        id: e._id,
                        name: e.name,
                        token,
                        imgurl: e.imgurl
                    }
                    return res.send({ status: 200, res: back, message: '登录成功' })
                } else {
                    return res.send({ status: 400, message: '密码错误' })
                }
            })
        }
    })
}
//搜索用户
exports.searchUser = (name, res) => {
    let sqlstr = 'select * from userschema  where name  like ? or email like ?'
    db.query(sqlstr, ['%' + name + '%', '%' + name + '%'], (err, res1) => {

        if (err) return res.send({ status: 500, message: c })
        const result =
            res1.map((v) =>
                ({ name: v.name, email: v.email, imgurl: v.imgurl, id: v._id, sign: v.sign })
            )
        return res.send({
            status: 200,
            res: result

        })
    })
}
//判断是否为好友
exports.isFriend = (uid, fid, res) => {
    let sqlstr = 'select * from friendschema  where userId=?&&friendId=?&&state=?   '
    db.query(sqlstr, [uid, fid, 0], (err, res1) => {
        if (err) return res.send({ status: 500 })

        return res1.length > 0 ? res.send({ status: 200, message: '是好友' }) : res.send({ status: 400, message: '不是好友' })


    })

}
//搜索群
exports.searchGroup = (name, res) => {
    let sqlstr = 'select * from groupschema  where name=? '
    db.query(sqlstr, name, (err, res1) => {

        if (err) return res.send({ status: 500, message: '' })
        return res.send({ status: 200, })
    })
}
//判断是否在群内
exports.isInGroup = (uid, fid, res) => {
    let sqlstr = 'select * from groupuserschema  where userid=?&&groupid=?   '
    db.query(sqlstr, [uid, fid], (err, res1) => {

        if (err) return res.send({ status: 500, message: '' })

        return res1.length ? res.send({ status: 200, message: '是好友' }) : res.send({ status: 400, message: '不是好友' })

    })
}
// 用户详情
exports.UserDetail = (id, res) => {
    let sqlstr = 'select * from userschema  where _id=?  '
    db.query(sqlstr, id, (err, res1) => {
        if (err) return res.send({ status: 500, message: res1 })
        return res.send({ status: 200, res1 })
    })
}
function updata(data, res) {
    let sqlstr = `UPDATE userschema SET ${data.type}=? WHERE id=?`
    db.query(sqlstr, [data.data, data.id], (err, res1) => {

        if (err) return res.send({ status: 500, message: err.sqlMessage })
        return res.send({ status: 200, message: '更新成功' })
    })
}
//用户信息修改
exports.userUpdate = (data, res) => {


    let updatestr = {}
    if (typeof (data.psw) !== 'undefined') {
        let sqlstr = 'select * from userschema  where _id=?  '
        db.query(sqlstr, data.userId, (err, res1) => {
            if (err) return res.send({ status: 500, message: err })
            if (!res1) {
                res.send({ status: 400 })
            } else {
                res1.map((e) => {
                    const pwdMatch = bcrypt.verification(data.psw, e.psw)
                    if (pwdMatch) {
                        if (data.type === 'psw') {

                            data.data = bcrypt.enctyption(data.data)
                        }
                        updatestr[data.type] = data.data
                        let sqlstr = `UPDATE userschema SET ${data.type}=?&userId=?   `
                        db.query(sqlstr, [data.data], (err, res1) => {
                            if (err) return res.send({ status: 500 })
                            if (res1.length > 0) {
                                return res.send({ status: 200, message: '已注册' })
                            } else {
                                updata(data, res)
                            }
                        })
                    } else {
                        res.send({ status: 400, message: '密码匹配失败' })
                    }
                })
            }
        })
    } else {


        // if (data.type == 'name' || data.type == 'email') {
        let sqlstr = `UPDATE userschema SET ${data.type}=? where _id=?`
        db.query(sqlstr, [data.data, data.userId], (err, res1) => {



            if (err) return res.send({ status: 500 })
            if (res1.length > 0) {


                return res.send({ status: 300, message: (data.type == 'name' ? '用户名' : '邮箱') + '已存在' })
            } else {
                updata(data, res)
            }

        })
        // }

    }
}
//修改好友昵称-
exports.friendMarkName = (data, res) => {

    let sqlstr = `UPDATE friendschema SET markname=? WHERE friendId=?&&userId=?`
    db.query(sqlstr, [data.name, data.friendId, data.userId], (err, res1) => {
        if (err) return res.send({ status: 500, message: res1 })
        return res.send({ status: 200, res: res1 })
    })
}

//获取好友昵称-
exports.GetfriendMarkName = (data, res) => {


    let sqlstr = `select * from friendschema  where friendId=?&&userId=?`
    db.query(sqlstr, [data.friendId, data.userId], (err, res1) => {

        if (err) return res.send({ status: 500, message: res1 })
        return res.send({ status: 200, res1 })
    })
}
//好友申请
exports.applyFriend = (data, res) => {
    console.log(data);


    let sqlstr = `select * from friendschema  where userId=? && friendId=?`
    db.query(sqlstr, [data.userId, data.friendId], (err, res1) => {



        if (err) return res.send({ status: 500, message: res1 })
        if (res1.length > 0) {
            console.log(1);

            this.upFriendLastTime(data.userId, data.friendId, res)
            this.upFriendLastTime(data.friendId, data.userId, res)
        } else {

            console.log(2);
            this.buildFriend(data.userId, data.friendId, 2, res)
            this.buildFriend(data.friendId, data.userId, 1, res)
        }
        this.insertMsg(data.userId, data.friendId, data.msg, 0, res)

    })
}
//添加好友表
exports.buildFriend = (uid, fid, state, res) => {


    let sqlstr = 'INSERT INTO friendschema (userId,friendId,state,time,lastTime) VALUES (?,?,?,?,?) '
    db.query(sqlstr, [uid, fid, state, new Date(), new Date()], (err, res1) => {

        console.log(err, 'err');


        if (err) return res.send({ status: 500, message: res1 })


        return console.log('添加成功');

    })
}

//添加一对一消息表
exports.insertMsg = (uid, fid, msg, type, res) => {
    let sqlstr = 'INSERT INTO messageschema (userId,friendId,message,types,time,state) VALUES (?,?,?,?,?,?) '
    db.query(sqlstr, [uid, fid, msg, type, new Date(), 1], (err, res1) => {
        if (err) return res.send({ status: 500, message: res1 })
        return res.send({ status: 200, message: '已发送消息' })
    })
}

//好友最后通讯时间更新
exports.upFriendLastTime = (uid, fid, res) => {


    const sqlstr = `UPDATE friendschema SET lastTime=? WHERE friendId=?&&userId=?`
    db.query(sqlstr, [new Date(), fid, uid], (err, res1) => {
        if (err) return res.send({ status: 500, message: res1 })
        return console.log('更新成功');
    })
}



//更新好友状态 同意
exports.updateFriendState = (data, res) => {


    const sqlstr = `UPDATE friendschema SET state=? WHERE (friendId=?&&userId=?)||(friendId=?&&userId=?)`
    db.query(sqlstr, [0, data.friendId, data.userId, data.userId, data.friendId], (err, res1) => {
        if (err) return res.send({ status: 500, message: res1 })

        return res.send({ status: 200, message: '添加成功' })
    })

}

//删除或拒绝
exports.deleteFriend = (data, res) => {


    const sqlstr = `DELETE friendschema  WHERE (friendId=?&&userId=?)||(userId=?&&friendId=?)`
    db.query(sqlstr, [data.friendId, data.userId, data.friendId, data.userId], (err, res1) => {
        if (err) return res.send({ status: 500, message: res1 })
        return res.send({ status: 200, message: '删除成功' })
    })

}

//按要求获取用户列表
exports.getUsers = (data, res) => {
    let sqlstr = `SELECT * FROM mydb01.friendschema inner join userschema on userId=?&&state=?&& friendschema.friendId = userschema._id ORDER BY friendschema.lastTime DESC;`
    db.query(sqlstr, [data.userId, data.state], (err, res1) => {
        if (err) return res.send({ status: 500 })
        let back = res1.map((v) => {
            return {
                id: v._id,
                name: v.name,
                markname: v.markname,
                imgurl: v.imgurl,
                lastTime: v.lastTime,
                type: 0
            }
        })

        return res.send({ status: 200, res: back })

    })
}
//获取一对一消息
exports.getOneMsg = async (data, res) => {


    let sqlstr = `SELECT * FROM messageschema where (userId=?&&friendId=?) || (friendId=?&&userId=?) ORDER BY time DESC`
    await db.query(sqlstr, [data.userId, data.friendId, data.userId, data.friendId], async (err, res1) => {


        if (err) return res.send({ status: 500 })
        back1 = res1.map((v) => {
            return {
                message: v.message,
                time: v.time,
                types: v.types
            }
        })
        return res.send({ status: 200, res: back1[0] })
    })
}

//汇总一对一消息未读数
exports.unrearMsg = (data, res) => {
    let sqlstr = `select * from messageschema  where friendId=?&&userId=?&&state=1 ORDER BY time DESC`
    db.query(sqlstr, [data.friendId, data.userId], (err, res1) => {
        if (err) return res.send({ status: 500, message: res1 })
        return res.send({ status: 200, res: res1 })

    })
}

//一对一消息状态修改
exports.updateMsg = (data, res) => {
    let sqlstr = `UPDATE messageschema SET state=0 WHERE friendId=?&&userId=?`
    db.query(sqlstr, [data.friendId, data.userId], (err, res1) => {
        if (err) return res.send({ status: 500, message: res1 })
        return res.send({ status: 200, message: '修改成功' })

    })
}
//新建群
exports.createGroup = (data, res) => {
    let sqlstr = 'INSERT INTO groupschema (userId,name,imgurl,time,groupId) VALUES (?,?,?,?,?) ';
    let sqlstr1 = 'select * from groupschema  where groupId=?';
    let groupId = 'group' + createId()
    db.query(sqlstr, [data.userId, data.name, data.imgurl, new Date(), groupId], (err, res1) => {
        console.log(err, '建群');

        if (err) { return res.send({ status: 500, message: res1 }) }
        else {

            db.query(sqlstr1, groupId, (err, res2) => {



                if (err) { return res.send({ status: 500, message: res2 }) }
                else {
                    console.log(res2);
                    let udata = {
                        groupId: groupId,
                        userId: data.userId,
                        time: new Date(),
                        lastTime: new Date()
                    }
                    this.insertGroupUser(udata, res);
                    res2.map((gid) => {

                        //添加好友进群
                        data.user.map((uid) => {
                            let fdata = {
                                groupId: gid.groupId,
                                userId: uid,
                                time: new Date(),
                                lastTime: new Date()
                            }
                            this.insertGroupUser(fdata, res);
                        })
                    })
                    return res.send({ status: 200, message: '创建成功' })

                }

            })

        }
        // return res.send({ status: 200, message: '新建成功' })
    })
}
//将群成员存进成员表
exports.insertGroupUser = (fdata, res) => {
    let sqlstr = 'INSERT INTO groupuserschema (groupId,userId,time,lastTime) VALUES (?,?,?,?) '
    db.query(sqlstr, [fdata.groupId, fdata.userId, new Date(), new Date()], (err, res1) => {
        if (err) { return res.send({ status: 500, message: res1 }) }
        else {
            // return res.send({ status: 200, message: '加入成功' })
        }
        // return res.send({ status: 200, message: '新建成功' })
    })
}
//按要求获取群列表
exports.getGroup = (data, res) => {
    let sqlstr = `SELECT * FROM groupuserschema inner join groupschema on userId=?&& groupuserschema.groupId = groupschema.groupId ORDER BY friendschema.lastTime DESC;`
    db.query(sqlstr, [data.userId], (err, res1) => {
        if (err) return res.send({ status: 500 })
        let back = res1.map((v) => {
            return {
                gid: v._id,
                name: v.name,
                markname: v.markname,
                imgurl: v.imgurl,
                lastTime: v.lastTime,
                type: 1
            }
        })

        return res.send({ status: 200, res: back })

    })
}

//获取群最后一条消息
exports.getGroupOneMsg = async (data, res) => {

    let sqlstr = `SELECT * FROM groupmsgschema inner join userschema on groupId=?&& groupmsgschema.userId = userschema._id ORDER BY friendschema.lastTime DESC;`
    await db.query(sqlstr, data.groupId, async (err, res1) => {
        if (err) return res.send({ status: 500 })
        back1 = res1.map((v) => {
            return {
                message: v.message,
                time: v.time,
                types: v.types,
                name: v.name
            }
        })
        return res.send({ status: 200, res: back1 })
    })
}

//群消息状态修改
exports.updateGroupMsg = (data, res) => {
    let sqlstr = `UPDATE groupmsgschema SET tip=0 WHERE groupId=?&&userId=?`
    db.query(sqlstr, [data.groupId, data.userId], (err, res1) => {
        if (err) return res.send({ status: 500, message: res1 })
        return res.send({ status: 200, message: '修改成功' })

    })
}

//分页获取一对一聊天数据
exports.msg = (data, res) => {
    let m = data.nowPage * data.pageSize;

    let n = data.pageSize
    // let sqlstr = `select * from messageschema order by userId limit 1, 1;`
    let sqlstr = `select * from messageschema   inner join userschema on ((userId=?&&friendId=?)||(friendId=?&&userId=?))&&messageschema.userId = userschema._id   ORDER BY messageschema.time DESC,userschema._id limit ?, ?`
    db.query(sqlstr, [data.userId, data.friendId, data.userId, data.friendId, data.nowPage, n], (err, res1) => {


        if (err) return res.send({ status: 500, message: res1 })


        let back = res1.map((v) => {
            return {
                id: v._id,
                message: v.message,
                types: v.types,
                time: v.time,
                fromId: v.userId
            }
        })
        return res.send({ status: 200, res: back })

    })
}
